import React from 'react'
import './login.scss'
import type { FormProps } from 'antd'
import { Button, Checkbox, Form, Input, Col, Row, Card, message } from 'antd'
import codeImg from '@/assets/imgs/code.png'

import { reqLogin } from '@/api/user'
import { getUserMenus } from '@/api/permission'

import { useNavigate } from 'react-router-dom'
import useUserStore from '@/store/user'

type FieldType = {
  loginName?: string
  loginPwd?: string
  remember?: string
  verificationCode?: string
}

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo)
}

const Login: React.FC = () => {
  const { setUserInfo, setToken } = useUserStore()
  const navigate = useNavigate()

  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    console.log('Success:', values)
    const data = {
      loginName: values.loginName || '',
      loginPwd: values.loginPwd || ''
    }
    
    try {
      const res = await reqLogin(data);
      console.log(res);

      if (!res.isSuc) {
        return message.error(res.message || '登录失败')
      }

      // 保存用户信息和token
      setUserInfo(res.data)
      setToken(res.data.token)
      
      message.success('登录成功')
      
      // 重定向到首页
      navigate('/')
      
      // 可选：重新加载页面以确保动态菜单正确加载
      // window.location.reload()
    } catch (error) {
      console.error('登录失败:', error)
      message.error('登录失败，请检查网络连接')
    }
  }
  
  return (
    <Card className="box">
      <Form
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        // initialValues={{ remember: true }}
        initialValues={{ loginName: 'admin', loginPwd: '123456',verificationCode: 'VRvT' }} // 设置初始值
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        validateTrigger="onBlur"
      >
        <h2>登录页面</h2>
        <Form.Item<FieldType>
          label="账号"
          name="loginName"
          rules={[
            { required: true, message: '请输入账号' },
            {
              pattern: /^\w{5,16}$/i,
              message: '账号应为5-15字母数字下划线组成'
            }
          ]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>

        <Form.Item<FieldType>
          label="密码"
          name="loginPwd"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item<FieldType>
          label="验证码"
          name="verificationCode"
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <Row>
            <Col span={14}>
              {' '}
              <Input placeholder="请输入验证码" />
            </Col>
            <Col span={10}>
              <img src={codeImg} />
            </Col>
          </Row>
        </Form.Item>

        <Form.Item<FieldType>
          name="remember"
          valuePropName="checked"
          label={null}
        >
          <Row>
            <Col span={12}>
              <Checkbox>记住我</Checkbox>
            </Col>
            <Col span={12} style={{ textAlign: 'right' }}>
              <a href="#">忘记密码</a>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item label={null} wrapperCol={{ offset: 18, span: 6 }}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </Card>
  )
}

export default Login
